<?php

namespace app\api\controller\order;

use app\BaseController;

use app\common\model\User\User as UserModel;
use app\common\model\Product\Product as ProductModel;
use app\common\model\Product\Type as TypeModel;
use app\common\model\Product\Vip as VipModel;
use app\common\model\Cart as CartModel;
use app\common\model\User\Address as AddressModel;
use app\common\model\User\Record as RecordModel;
use app\common\model\Order\Order as OrderModel;
use app\common\model\Order\Product as OrderProductModel;

use app\common\validate\Order\Order as OrderValidate;
use app\common\validate\Order\Product as OrderProductValidate;
use app\common\validate\User\Record as RecordValidate;
use think\exception\ValidateException;


class Order extends BaseController
{
    public function initialize()
    {
        parent::initialize();

        $this->UserModel = new UserModel();
        $this->TypeModel = new TypeModel();
        $this->ProductModel = new ProductModel();
        $this->VipModel = new VipModel();
        $this->CartModel = new CartModel();
        $this->AddressModel = new AddressModel();
        $this->RecordModel = new RecordModel();
        $this->OrderModel = new OrderModel();
        $this->OrderProductModel = new OrderProductModel();
    }

    // 下单 
    public function add()
    {
        if ($this->request->isPost()) {

            //接收参数
            $userid = $this->request->param('userid', 0);
            $addrid = $this->request->param('addressid', 0);
            $cartids = $this->request->param('cartids', '');
            $content = $this->request->param('content', '');
            $ispromptly = $this->request->param('ispromptly', '');
            $cartid = explode(',', $cartids) ? explode(',', $cartids) : '';

            //先判断用户是否存在
            $user = $this->UserModel->find($userid);

            if (!$user) {
                $this->error('用户不存在');
                exit;
            }

            $where = [
                'id' => $addrid,
                'userid' => $userid
            ];

            //判断收货地址是否存在
            $address = $this->AddressModel->where($where)->find();

            if (!$address) {
                $this->error('收货地址不存在，请重新选择');
                exit;
            }


            $where = [
                'cart.id' => $cartid,
                'userid' => $userid
            ];

            if ($ispromptly) {
                $product = $this->ProductModel->with(['type'])->find($cartids);

                $cartlist[] = [
                    'total' => $product['price'],
                    'product' => $product,
                    'proid' => $product['id'],
                    'nums' => 1,
                    'price' => $product['price'],
                    'userid' => $userid
                ];
            } else {
                // 查询购物车的产品数据
                $cartlist = $this->CartModel->withJoin(['product'], 'LEFT')->where($where)->select();
            }
            // echo $this->CartModel->getLastSql();exit;


            if (!$cartlist) {
                $this->error('下单数据为空，请重新选择商品');
                exit;
            }

            //判断商品库存是否充足
            foreach ($cartlist as $item) {

                //购物车的数量 和商品的库存
                $nums = $item['nums'];
                $stock = $item['product']['stock'];

                //让库存 - 购物车数量
                $pronums = bcsub($stock, $nums);

                if ($pronums < 0) {

                    $this->error($item['product']['name'] . "库存不足，请重新选择");
                    exit;
                }
            }


            //查询下单数据的总价格
            $where = [
                'id' => $cartid,
                'userid' => $userid
            ];

            if ($ispromptly) {
                $total = $cartlist[0]['total'];
            } else {
                $total = $this->CartModel->where($where)->sum('total');
            }
            // echo $this->CartModel->getLastSql();exit;

            //用户积分
            $point = $user['point'];


            //让用户积分 -  总价
            $UpdatePoint = bcsub($point, $total);

            if ($UpdatePoint < 0) {
                $this->error('积分不足，请充值后操作');
                exit;
            }

            //订单表(INSERT) 订单商品表(INSERT) 商品库存(update) 用户积分(update) 消费记录(insert) 购物车(delete)

            //开启事务
            $this->OrderModel->startTrans();
            $this->OrderProductModel->startTrans();
            $this->ProductModel->startTrans();
            $this->UserModel->startTrans();
            $this->RecordModel->startTrans();
            $this->CartModel->startTrans();

            //组装订单表数据
            $OrderData = [
                'userid' => $userid,
                'addrid' => $addrid,
                'code' => build_code("AK"),  //ask => AK
                'content' => $content,
                'status' => 1,
                'total' => $total
            ];


            try {
                validate(OrderValidate::class)->check($OrderData);
                //订单表 validate('common/Order/Order')->
                $OrderStatus = $this->OrderModel->save($OrderData);
            } catch (ValidateException $e) {
                // 捕获异常
                $this->error($e->getError());
                exit;
            }
            

            if ($OrderStatus === FALSE) {
                $this->error($this->OrderModel->getError());
                exit;
            }


            //组装订单商品的数据
            $OrderProductData = [];
            $ProductData = [];

            foreach ($cartlist as $item) {
                //订单商品
                $OrderProductData[] = [
                    'orderid' => $this->OrderModel->id,
                    'proid' => $item['proid'],
                    'nums' => $item['nums'],
                    'price' => $item['price'],
                    'total' => $item['total'],
                ];


                //商品库存 - 购物车数量
                $stock = bcsub($item['product']['stock'], $item['nums']);

                //商品库存
                $ProductData[] = [
                    'id' => (string)$item['proid'],
                    'stock' => $stock,
                ];
            }

            // 二维数组，用的循环校验数组
            $OrderShow = true;
            foreach ($OrderProductData as $value) {
                try {
                    validate(OrderProductValidate::class)->check($value);

                } catch (ValidateException $e) {
                    // 捕获异常
                    $this->error($e->getError());
                    $OrderShow = false;
                    exit;
                }
            }

            if( $OrderShow == true ) {
                //插入订单商品表  validate('common/Order/Product')->
                $OrderProductStatus = $this->OrderProductModel->saveAll($OrderProductData);
            }
            

            if ($OrderProductStatus === FALSE) {
                //回滚
                $this->OrderModel->rollback();
                $this->error($this->OrderProductModel->getError());
                exit;
            }


            //商品更新库存  批量saveAll
            $ProductStatus = $this->ProductModel->saveAll($ProductData);


            if ($ProductStatus === FALSE) {
                //回滚
                $this->OrderProductModel->rollback();
                $this->OrderModel->rollback();
                $this->error($this->ProductModel->getError());
                exit;
            }


            //更新用户积分
            $UserData = [
                'id' => $userid,
                'point' => $UpdatePoint
            ];

            $UserStatus = $this->UserModel->update($UserData);

            if ($UserStatus === FALSE) {
                //回滚
                $this->ProductModel->rollback();
                $this->OrderProductModel->rollback();
                $this->OrderModel->rollback();
                $this->error($this->UserModel->getError());
                exit;
            }


            // 消费记录
            $RecordData = [
                'point' => $total,
                'content' => "订单号：" . $OrderData['code'] . "---消费的积分为：$total",
                'state' => 5,
                'userid' => $userid
            ];

            // validate('common/User/Record')

            try {
                validate(RecordValidate::class)->check($RecordData);

                $RecordStatus = $this->RecordModel->save($RecordData);

            } catch (ValidateException $e) {
                // 捕获异常
                $this->error($e->getError());
                exit;
            }

           
            if ($RecordStatus === FALSE) {
                //回滚
                $this->UserModel->rollback();
                $this->ProductModel->rollback();
                $this->OrderProductModel->rollback();
                $this->OrderModel->rollback();
                $this->error($this->RecordModel->getError());
                exit;
            }

            // 购物车(delete)
            $CartStatus = $this->CartModel->destroy($cartid);

            if ($CartStatus === FALSE) {
                //回滚
                $this->RecordModel->rollback();
                $this->UserModel->rollback();
                $this->ProductModel->rollback();
                $this->OrderProductModel->rollback();
                $this->OrderModel->rollback();
                $this->error($this->CartModel->getError());
                exit;
            }

            if ($OrderStatus !== FALSE && $OrderProductStatus !== FALSE && $ProductStatus !== FALSE && $UserStatus !== FALSE && $RecordStatus !== FALSE && $CartStatus !== FALSE) {
                //提交事务
                $this->OrderModel->commit();
                $this->OrderProductModel->commit();
                $this->ProductModel->commit();
                $this->UserModel->commit();
                $this->RecordModel->commit();
                $this->CartModel->commit();

                $this->success('下单成功，等待商家发货', '/user/order/index');
                exit;
            } else {
                //回滚
                $this->CartModel->rollback();
                $this->RecordModel->rollback();
                $this->UserModel->rollback();
                $this->ProductModel->rollback();
                $this->OrderProductModel->rollback();
                $this->OrderModel->rollback();
                $this->error('下单失败,请重新操作');
                exit;
            }
        }
    }

    // 订单列表
    public function index()
    {
        if ($this->request->isPost()) {
            $userid = $this->request->param('userid', 0);
            $status = $this->request->param('status', 0);

            $userinfo = $this->UserModel->find($userid);

            //当没有找到用户的情况下
            if (!$userinfo) {
                $this->error('用户不存在，请重新输入');
                exit;
            }

            $where = [];
            // 判断订单类型
            if ($status != 0) {
                $where['status'] = $status;
            }

            $where['userid'] = $userid;

            // 订单信息
            $result = $this->OrderModel->where($where)->order('id', 'DESC')->select();

            if (!$result) {
                $this->success('暂无订单数据');
                exit;
            }

            $orderlist = [];

            foreach ($result as $item) {

                //组装订单数据
                $info = [
                    'id' => $item['id'],
                    'code' => $item['code'],
                    'total' => $item['total'],
                    'createtime' => $item['createtime'],
                    'status' => $item['status'],
                    'status_text' => $item['status_text'],
                ];

                //获取订单中的第一个商品
                $product = $this->OrderProductModel->with('info')->where(['orderid' => $item['id']])->find();

                // 判断订单中产品的结果，第二个是否有这个产品
                if ($product && $product['info']['id']) {
                    $info['product'] = $product['info'];
                }
                $orderlist[] = $info;
            }

            $this->success('返回订单数据', null, $orderlist);
            exit;
        }
    }

    // 订单详情
    public function info()
    {

        if ($this->request->isPost()) {
            $userid = $this->request->param('userid', 0);
            $id = $this->request->param('orderid', 0);

            $userinfo = $this->UserModel->find($userid);

            //当没有找到用户的情况下
            if (!$userinfo) {
                $this->error('用户不存在，请重新输入');
                exit;
            }

            $express = $this->OrderModel->withJoin(['express'], 'LEFT')->where(['order.id' => $id])->value('name');

            $orderinfo = $this->OrderModel->find($id);
            // 

            if ($express) {
                $orderinfo['name'] = $express;
            }

            if (!$orderinfo) {
                $this->error('订单不存在，请去下单');
                exit;
            }


            //订单商品 name,expcode
            $product = $this->OrderProductModel->with('info')->where(['orderid' => $id])->select();


            //判断订单商品是否存在
            if (!$product) {
                $this->error('订单商品不存在');
                exit;
            }

            //获取订单的收货地址 with(['userProfile','userBook'])
            $address = $this->AddressModel->with(['provinces', 'citys', 'districts'])->find($orderinfo['addrid']);
            

            if (!$address) {
                // $this->error('未找到订单的收货地址');
                // exit;
                $address = [
                    
                ];
            }

            $data = [
                'order' => $orderinfo,
                'product' => $product,
                'address' => $address
            ];

            $this->success('返回订单数据成功', null, $data);
            exit;
        }
    }

    // 确认收货
    public function receiving()
    {
        if ($this->request->isPost()) {
            $userid = $this->request->param('userid', 0);
            $id = $this->request->param('orderid', 0);

            $userinfo = $this->UserModel->find($userid);

            //当没有找到用户的情况下
            if (!$userinfo) {
                $this->error('用户不存在，请重新输入');
                exit;
            }

            $orderinfo = $this->OrderModel->find($id);

            if (!$orderinfo) {
                $this->error('订单不存在，请去下单');
                exit;
            }

            $data = [
                'id' => $id,
                'status' => 3
            ];

            $result = $this->OrderModel->update($data);

            if ($result === FALSE) {
                $this->error($this->OrderModel->getError());
                exit;
            } else {
                $this->success('确认收货成功', null);
                exit;
            }
        }
    }

    // 退货
    public function retreat()
    {
        if ($this->request->isPost()) {
            $userid = $this->request->param('userid', 0);
            $id = $this->request->param('orderid', 0);

            $userinfo = $this->UserModel->find($userid);

            //当没有找到用户的情况下
            if (!$userinfo) {
                $this->error('用户不存在，请重新输入');
                exit;
            }

            $orderinfo = $this->OrderModel->find($id);

            if (!$orderinfo) {
                $this->error('订单不存在，请去下单');
                exit;
            }

            $data = [
                'id' => $id,
                'status' => '-2'
            ];

            $result = $this->OrderModel->update($data);

            if ($result === FALSE) {
                $this->error($this->OrderModel->getError());
                exit;
            } else {
                $this->success('申请退货中,需要审核,请等待1-2天,', null);
                exit;
            }
        }
    }

    // 评分
    public function rate()
    {
        if ($this->request->isPost()) {

            $params = $this->request->param();
            $userid = $this->request->param('userid', 0);
            $data = $this->request->param('data', '');
            $id = $this->request->param('orderid', 0);

            $userinfo = $this->UserModel->find($userid);
           
            // halt($params);
            //当没有找到用户的情况下
            if (!$userinfo) {
                $this->error('用户不存在，请重新输入');
                exit;
            }

            $orderinfo = $this->OrderModel->find($id);

            if (!$orderinfo) {
                $this->error('订单不存在，请去下单');
                exit;
            }

            if ($data) {

                $data = json_decode($data);
                $ProductData = [];
                foreach ($data as $item) {
                    // $item = json_decode($item);
                    // halt($item->id);

                    if(isset($item->proid) && $item->proid){
                        $result =  uploads($item->proid) ? uploads($item->proid) : upload($item->proid);
                        // ($result['data']);
                        
                    }
                    
                    $ProductData[] = [
                        'id' => (string)$item->id,
                        'rate' => (string)$item->rate,
                        'comment' => $item->comment,
                        'userid' => $userid,
                        'proimg' => isset($result['data']) ?  implode(",",$result['data']): ''
                    ];
                   
                }
              
                //开启事务
                $this->OrderModel->startTrans();
                $this->OrderProductModel->startTrans();

                $OrderData = [
                    'id' => (string)$id,
                    'status' => 4
                ];

                
                $OrderStatus = $this->OrderModel->update($OrderData);

                if ($OrderStatus === FALSE) {
                    $this->error($this->OrderModel->getError());
                    exit;
                }
                // halt($ProductData);

                $result = $this->OrderProductModel->saveAll($ProductData);

                if ($result === FALSE) {
                    //回滚
                    $this->OrderProductModel->rollback();
                    $this->OrderModel->rollback();
                    $this->error($this->CartModel->getError());
                    exit;
                }
                if ($OrderStatus !== FALSE && $result !== FALSE) {
                    //提交事务
                    $this->OrderModel->commit();
                    $this->OrderProductModel->commit();
                    $this->success('评价成功');
                    exit;
                } else {
                    //回滚
                    $this->OrderProductModel->rollback();
                    $this->OrderModel->rollback();
                    $this->error('评价失败');
                    exit;
                }
            }
        }
    }

    //查看物流信息
    public function express()
    {
        if ($this->request->isPost()) {
            $orderid = $this->request->param('orderid', 0);
            $userid = $this->request->param('userid', 0);

            //组装条件
            $where = [
                'userid' => $userid,
                'order.id' => $orderid
            ];

            //查询订单是否存在
            $order = $this->OrderModel->withJoin(['express'], 'LEFT')->where($where)->find();

            if (!$order) {
                $this->error('订单不存在');
                exit;
            }

            //判断是否有快递单号
            if (empty($order['expcode'])) {
                $this->error('暂无快递单号');
                exit;
            }

            //调用接口
            // $result = QueryExpress(trim($order['expcode']));

            $result = '{
                  "showapi_res_error": "",
                  "showapi_res_id": "627dcd820de376a006d84ead",
                  "showapi_res_code": 0,
                  "showapi_fee_num": 1,
                  "showapi_res_body": {"queryTimes":5,"upgrade_info":"","fee_num":1,"status":4,"expSpellName":"yuantong","msg":"查询成功","updateStr":"2022-05-13 11:16:18","possibleExpList":[],"flag":true,"tel":"021-69777888/95554","ret_code":0,"logo":"http://static.showapi.com/app2/img/expImg/yuantong.jpg","expTextName":"圆通速递","data":[{"context":"客户签收人: 【丰巢】新港西路205号大院出入口右侧丰巢柜已签收 已签收  感谢使用圆通速递，期待再次为您服务 如有疑问请联系：13112214298，投诉电话：07967711259 疫情期间圆通每天对网点多次消毒，快递小哥新冠疫苗已接种，每天测量体温，佩戴口罩","time":"2022-04-27 19:00:35"},{"context":"您的快件已存放至【新港西路205号新港西路205号大院出入口右侧丰巢柜】【新港西路205号大院出入口右侧丰巢柜】,请及时取件。若有疑问，请电联派件员【13112214298】","time":"2022-04-27 10:56:35"},{"context":"【广东省广州市海珠区珠江广场公司】 派件中  派件人: 黄嘉桐 电话 13112214298 圆通快递小哥新冠疫苗已接种，每天已测体温，请放心收寄快递 如有疑问，请联系：07967711080","time":"2022-04-27 07:56:37"},{"context":"【广东省广州市海珠区珠江广场公司】 已收入","time":"2022-04-27 07:18:57"},{"context":"【广州转运中心】 已发出 下一站 【广东省广州市海珠区珠江广场公司】","time":"2022-04-27 04:41:34"},{"context":"【广州转运中心公司】 已打包","time":"2022-04-27 04:25:06"},{"context":"【广州转运中心公司】 已收入","time":"2022-04-27 04:11:44"},{"context":"【江门转运中心】 已发出 下一站 【广州转运中心公司】","time":"2022-04-26 22:53:12"},{"context":"【江门转运中心公司】 已收入","time":"2022-04-26 22:52:17"},{"context":"【广东省中山市中山北】 已发出 下一站 【江门转运中心公司】","time":"2022-04-26 19:45:26"},{"context":"【广东省中山市中山北公司】 已打包","time":"2022-04-26 19:32:38"},{"context":"【广东省中山市中山北公司】 已收入","time":"2022-04-26 19:32:28"},{"context":"【广东省中山市中山北公司】 已揽收 取件人: 唐志人 (18022133158)新冠疫苗已接种","time":"2022-04-26 19:17:00"}],"mailNo":"YT6449274918010","dataSize":13,"update":1652411778898}
              }';

            $arr = json_decode($result, true);

            if (!is_array($arr)) {
                $this->error('物流信息查询失败');
                exit;
            }

            $data = isset($arr['showapi_res_body']['data']) ? $arr['showapi_res_body']['data'] : [];

            if (empty($data)) {
                $this->error('暂无物流信息');
                exit;
            }

            $this->success('返回物流信息', null, $data);
            exit;
        }
    }
}
